package org.bot.server.client.controller;

import com.alibaba.fastjson.JSONObject;
import org.bot.server.client.service.BotClientService;
import org.bot.server.config.LoginCache;
import org.bot.server.utils.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 沧月
 * @create 0020 2023/9/20 09:57
 * @description <description class purpose>
 */
@RestController
@RequestMapping("/bot-client")
public class BotClientController extends BaseController {

    @Autowired
    BotClientService clientService;

    @RequestMapping("/list")
    public JSONObject list(int page, int size, String name) {
        return sendData(new JSONObject()
                .fluentPut("data", clientService.getBotClientList(page, size, name))
                .fluentPut("count", clientService.getBotClientListCount(name)));
    }

    @RequestMapping("/save")
    public JSONObject save(String clientName) {
        if (clientName == null) {
            return sendError("客户端名称不能为空");
        }
        if (clientService.save(clientName)) {
            return sendOK();
        } else {
            return sendError("保存失败");
        }
    }


    @RequestMapping("/delete")
    public JSONObject delete(Integer id) {
        if (id == null) {
            return sendError("客户端主键不能为空");
        }
        if (clientService.delete(id)) {
            return sendOK();
        } else {
            return sendError("删除失败，请检查是否关联流程");
        }
    }

    @RequestMapping("/edit")
    public JSONObject save(String clientName, Integer id) {
        if (clientName == null || id == null) {
            return sendError("参数错误");
        }
        if (clientService.edit(clientName, id)) {
            return sendOK();
        } else {
            return sendError("编辑失败");
        }
    }

    @RequestMapping("/disable")
    public JSONObject disable(String clientId, Integer status) {
        if (clientId == null || status == null) {
            return sendError("参数错误");
        }
        if (clientService.disable(clientId, status)) {
            return sendOK();
        } else {
            return sendError("禁用失败");
        }
    }

    @RequestMapping("/downCertificate")
    public void downCertificate(HttpServletResponse response, String id, String token) {
        if (!LoginCache.isLoginValid(token)) {
            return;
        }
        this.clientService.downCertificate(response, id);
    }

    @RequestMapping("/interruptAllTask")
    public JSONObject interruptAllTask(String clientId) {
        if (clientId == null) {
            return sendError("参数错误");
        }
        if (clientService.interruptAllTask(clientId)) {
            return sendOK();
        } else {
            return sendError("中断失败");
        }
    }
}
